package com.dev.service.shiro.realm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import com.dev.facade.entity.SyUserInfo;
import com.dev.facade.service.SyUserInfoService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @Description 自定义域
 * @author Shiwen .Li
 * @date 2016年7月17日 下午3:55:40
 * @version V1.3.1
 */
public class MyShiroRealm extends AuthorizingRealm {

	/**
	 * 日志记录
	 */
	protected Logger log = LoggerFactory.getLogger(this.getClass());

	/**
	 * 
	 */
	@Resource
	private SyUserInfoService userService;


	/**
	 * 获取授权信息
	 * 
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		// 根据自己系统规则的需要编写获取授权信息，这里为了快速入门只获取了用户对应角色的资源url信息
		String username = (String) pc.fromRealm(getName()).iterator().next();
		if (username != null) {

			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			
			//拥有的角色
			Set<String> roles=new HashSet<String>();
			
			//拥有的拥有的资源
			Set<String> stringPermissions=new HashSet<String>();
			
			info.setRoles(roles);
			
			info.setStringPermissions(stringPermissions);

			return info;
		}
		return null;
	}

	/**
	 * 获取认证信息
	 * 
	 * @param at
	 * @returnfx
	 * @throws AuthenticationException
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at)
			throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) at;
		// 通过表单接收的用户名
		String username = token.getUsername();
		if (!StringUtils.isEmpty(username)) {
			SyUserInfo user = new SyUserInfo();
			user.setAccount(username);
			user.setStatus(1);
			List<SyUserInfo> users = userService.selectList(user);
			log.info("结果信息", users);
			if (users != null && !users.isEmpty()) {
				user = users.get(0);
				return new SimpleAuthenticationInfo(user.getAccount(),
						user.getPassword(), getName());
			}
		}
		return null;
	}

}
